//
//  HomeProductASDataManager.m
//  iOS_Store_V2
//
//  Created by Gary on 28/06/2017.
//  Copyright © 2017 czy. All rights reserved.
//

#import "HomeProductASDataManager.h"
#import "HomeASProductItem.h"



@interface HomeProductASDataManager ()

@property (nonatomic, strong) CollectionViewReloadCompletionBlock completionBlock;

@end

@implementation HomeProductASDataManager


- (void)cellViewClickHandler:(id)item actionType:(NSInteger)actionType {

    if ([self.collectionViewDataSource.delegate respondsToSelector:@selector(actionOnView:actionType:)]) {
        [self.collectionViewDataSource.delegate actionOnView:item actionType:actionType];
    }
}

- (void)reloadView {
    NSLog(@"reloadView ------");
    [self reloadView:self.reponseDictionary block:self.completionBlock];
}

- (void)reloadView:(NSDictionary *)result block:(CollectionViewReloadCompletionBlock)completionBlock {
    NSLog(@"result = %@",result);
    __weak __typeof (self) weakSelf = self;
    dispatch_async(self.serialQueue, ^{
        @autoreleasepool {
            NSError *error = nil;
            
            self.reponseDictionary = result;
            self.completionBlock = completionBlock;
            self.collectionViewDataSource.totalPage = 5;
        
            NSData *statisticsData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"productList" ofType:@"json"]];
            NSArray *dataArray = [NSJSONSerialization JSONObjectWithData:statisticsData options:NSJSONReadingAllowFragments error:nil];

            
            [self configureSection];
            ASBBCollectionViewSection *section = self.section;
            if (weakSelf.collectionViewDataSource.currentPage == 1) {
            }
            
            if (!self.reloaded) {
                self.currentPage++;
            }else {
                self.currentPage = 0;
            }
            
            [self.addIndexPathArray removeAllObjects];
            
            
            NSInteger currentCount = 0;
            for (int i = self.currentPage * 20; i < MIN((self.currentPage + 1) * 20, dataArray.count);i++) {
                NSDictionary *entry = [dataArray objectAtIndex:i];
                if (![entry isKindOfClass:[NSDictionary class]]) {
                    continue;
                }
                HomeProductListModel *model = [HomeProductListModel modelWithDictionary:entry];

                


                    HomeASProductItem *item = [HomeASProductItem itemWithModel:model
                                                                  clickHandler:weakSelf.cellViewClickHandler
                                                              selectionHandler:weakSelf.selectionHandler];

                    if ((i + weakSelf.collectionViewDataSource.itemCount) % 2) {
                        item.sectionRightPadding = 10;
                        item.sectionLeftPadding = 0;
                    }else {
                        item.sectionRightPadding = 0;
                        item.sectionLeftPadding = 10;
                    }
                    [section addItem:item];
                    currentCount++;
                    NSInteger itemIndex = [section.items indexOfObject:item];
                    [self.addIndexPathArray addObject:[NSIndexPath indexPathForItem:itemIndex inSection:0]];
                


            }
            
            [weakSelf updateCollectionViewData:section];
            NSLog(@"currentCount = %@",@(currentCount));
            weakSelf.collectionViewDataSource.itemCount += currentCount;
            completionBlock(YES,nil,nil,currentCount);
        }
        
    });
}


-(void)refreshCell:(NSInteger)actionType dataId:(NSString *)dataId{
    if (!self.currentIndexPath) {
        return;
    }
    ASBBCollectionViewSection *section =[[self.collectionViewDataSource.asManager sections]objectAtIndex:self.currentIndexPath.section];
    if (section && [[section items] count] > 0 && section.items.count > self.currentIndexPath.row) {
        //刷新
        [self.collectionViewDataSource.asCollectionView reloadItemsAtIndexPaths:@[self.currentIndexPath]];
    }
    
}


-(void)selectionHandler:(TTSCollectionViewItem *)item{
    self.currentIndexPath = item.indexPath;
    NSLog(@"selectionHandler");
    
    
}



- (void)configureSection {
    
    
    if (!self.section) {
        self.section = [ASBBCollectionViewSection section];
        ASBBCollectionViewSection *tts_section = (ASBBCollectionViewSection*)self.section;
        tts_section.minimumLineSpace = 0;
        tts_section.minimumInteritemSpacing = 5;
        CGFloat topInset = 0;
        tts_section.sectionEdgeInsets = UIEdgeInsetsMake(topInset, 0, 0, 0);
    }else {
        ASBBCollectionViewSection *tts_section = (ASBBCollectionViewSection*)self.section;
        if (!tts_section.headerItem) {
            tts_section.minimumLineSpace = 0;
            tts_section.minimumInteritemSpacing = 5;
            CGFloat topInset = 0;
         
            tts_section.sectionEdgeInsets = UIEdgeInsetsMake(topInset, 0, 0, 0);

        }
    }
    
}

- (void)updateCollectionViewData:(id)section {
    dispatch_async(dispatch_get_main_queue(), ^{

        if (section == self.headerSection) {

        }else {
            if (![self.collectionViewDataSource.asManager.sections containsObject:section]) {
                [self.collectionViewDataSource.asManager addSection:section];
                [self.collectionViewDataSource.asCollectionView reloadData];
            }else {
                if (self.collectionViewDataSource.currentPage != 1) {
                    [self.collectionViewDataSource.asCollectionView performBatchAnimated:YES updates:^{
                        [self.collectionViewDataSource.asCollectionView insertItemsAtIndexPaths:self.addIndexPathArray];
                    } completion:self.collectionViewDataSource.asBtchCompletionBlock];
                }else {
                    [self.collectionViewDataSource.asCollectionView performBatchAnimated:YES updates:^{
                        [self.collectionViewDataSource.asCollectionView reloadSections:[NSIndexSet indexSetWithIndex:0]];
                    } completion:^(BOOL finished){
                        
                    }];
                }
            }
        }
        
    });
}

@end
